<?php

namespace Admin\Model;

use Think\Model;

class MemberModel extends Model
{
    protected $insertFields = array('username', 'password', 'phone', 'retime', 'vipid', 'viptime', 'domain');
    protected $updateFields = array('id', 'username', 'password', 'phone', 'retime', 'vipid', 'viptime', 'domain');
    protected $_validate = array(
        array('username', 'require', '用户名不能为空！', 1, 'regex', 3),
        array('username', '1,18', '用户名的值最长不能超过 18 个字符！', 1, 'length', 3),
        array('password', 'require', '密码不能为空！', 1, 'regex', 1),
        array('password', '1,32', '密码的值最长不能超过 32 个字符！', 1, 'length', 1),
        array('phone', 'require', '手机号不能为空！', 1, 'regex', 3),
        array('phone', '1,11', '手机号的值最长不能超过 11 个字符！', 1, 'length', 3),
        array('domain', 'require', '所在域名位置不能为空！', 1, 'regex', 2),
        array('domain', '1,50', '所在域名位置的值最长不能超过 50 个字符！', 1, 'length', 2),
    );

    public function search($pageSize = 15)
    {
        /**************************************** 搜索 ****************************************/
        $where = array();
        if ($username = I('get.username'))
            $where['username'] = array('like', "%$username%");
        if ($phone = I('get.phone'))
            $where['phone'] = array('like', "%$phone%");

        /************************************* 翻页 ****************************************/
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count, $pageSize);
        // 配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/
        $data['data'] = $this->alias('a')->field('a.*,b.agentname,c.name as vipname')->join('left join __AGENT__ b on a.domain=b.id left join __VIP__ c on c.id=a.vipid')->where($where)->group('a.id')->limit($page->firstRow . ',' . $page->listRows)->select();
        return $data;
    }

    // 添加前
    protected function _before_insert(&$data, $option)
    {
        $data['domain'] = str_replace('，', ',', $data['domain']);
        $data['password'] = md5($data['password']);
        $data['retime'] = time();
    }

    // 修改前
    protected function _before_update(&$data, $option)
    {
        $data['domain'] = str_replace('，', ',', $data['domain']);
        if ($data['password'])
            $data['password'] = md5($data['password']);
        else
            unset($data['password']);
    }

    // 删除前
    protected function _before_delete($option)
    {
        if (is_array($option['where']['id'])) {
            $this->error = '不支持批量删除';
            return FALSE;
        }
    }
    /************************************ 其他方法 ********************************************/
}